<template>
  <div class="product-add">
    <el-card class="box-card">
      <div slot="header">
        <span>新增商品</span>
      </div>
      <el-form
        ref="productForm"
        :model="productForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品图片" prop="imageFile">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="handleUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="productForm.supplierName" placeholder="请输入供应商" />
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            :precision="0"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addProduct } from '@/api/products'

export default {
  name: 'ProductAdd',
  data() {
    return {
      productForm: {
        productName: '',
        supplierName: '',
        price: 0,
        stock: 0
      },
      imageUrl: '',
      imageFile: null,
      rules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        supplierName: [
          { required: true, message: '请输入供应商', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    handleUpload(options) {
      this.imageFile = options.file
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageUrl = e.target.result
      }
      reader.readAsDataURL(options.file)
    },
    submitForm() {
      this.$refs.productForm.validate(async (valid) => {
        if (valid) {
          try {
            const formData = new FormData()
            Object.keys(this.productForm).forEach(key => {
              formData.append(key, this.productForm[key])
            })
            if (this.imageFile) {
              formData.append('imageFile', this.imageFile)
            }

            const res = await addProduct(formData)
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.goBack()
            } else {
              this.$message.error(res.message || '添加失败')
            }
          } catch (error) {
            console.error('添加商品错误:', error)
            this.$message.error('添加失败')
          }
        }
      })
    },
    goBack() {
      this.$router.push('/products')
    }
  }
}
</script>

<style lang="less" scoped>
.product-add {
  padding: 20px;

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;

    &:hover {
      border-color: #409EFF;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style> 